﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// n秒后，调用某函数
/// 
/// 允许在回调函数中，向scheduleList添加新元素，但不可以在回调中删除元素！
/// </summary>
public class ScheduleObject  {
    protected ScheduleObject()
    {

    }

    class Elem
    {
        /// <summary>
        /// 延迟时间
        /// </summary>
        public float mTime;

        /// <summary>
        /// 回调函数
        /// </summary>
        public System.Action mDel;

        /// <summary>
        /// 剩余时间
        /// </summary>
        public float leftTime;
    }

    List<Elem> scheduleList = new List<Elem>();

    static public ScheduleObject Create()
    {
        return new ScheduleObject();
    }

    public void AddSchedule(float time, System.Action del)
    {
        var elem = new Elem();
        elem.mTime = time;
        elem.mDel = del;
        elem.leftTime = time;
        scheduleList.Add(elem);
    }

    public void Update(float deltaTime)
    {
        int count = scheduleList.Count;
        int i = 0; 
        while(i < count)
        {
            var elem = scheduleList[i];
            elem.leftTime -= deltaTime;
            if (elem.leftTime <= 0)
            {
                scheduleList.RemoveAt(i);
                elem.mDel();
                count = scheduleList.Count;
            }
            else
                i++;
        }
    }

    public void Clear()
    {
        scheduleList.Clear();
    }
}

public class GlobalSchedule : ISubModule
{
    static GlobalSchedule s_instance;

    public static GlobalSchedule Instance
    {
        get
        {
            if(s_instance == null)
            {
                s_instance = new GlobalSchedule();
            }
            return s_instance;
        }
    }

    public void AddSchedule(float time, System.Action del)
    {
        mSch.AddSchedule(time, del);
    }

    public void Clear()
    {
        mSch.Clear();
    }

    void ISubModule.Init()
    {
    }

    void ISubModule.Start()
    {
    }

    void IUpdate.Update()
    {
        mSch.Update(RealTime.deltaTime);
    }

    void IPurge.PrePurge()
    {
    }

    void IPurge.Purge()
    {
    }

    ScheduleObject mSch = ScheduleObject.Create();
}